import re
from flask import request


class Devices(object):
    def __init__(self, app=None):
        if app is not None:
            self.app = app
            self.patterns = []
            self.init_app(app)

    def init_app(self, app):
        devices = app.config.get('DEVICES', [])

        for d in devices:
            self.add_pattern(d[0], d[1])

        @app.before_request
        def _template_changer():
            self.process_request(request)

    def process_request(self, request):
        user_agent = request.user_agent.string.lower()
        match = [(key, pattern) for key, pattern in self.patterns if
                 pattern.search(user_agent) is not None]
        if match:
            request.DEVICE = match[0][0]

    def add_pattern(self, group_name, pattern):
        pattern_complied = re.compile(pattern.lower())
        self.patterns.append((group_name, pattern_complied))